package com.lehecai.core.lottery.fetcher.lotterydraw.impl.worker;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.HasAttributeFilter;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.tags.LinkTag;
import org.htmlparser.tags.OptionTag;
import org.htmlparser.tags.ParagraphTag;
import org.htmlparser.tags.TableColumn;
import org.htmlparser.tags.TableRow;
import org.htmlparser.tags.TableTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.lehecai.core.lottery.LotteryType;
import com.lehecai.core.lottery.fetcher.lotterydraw.LotteryDraw;
import com.lehecai.core.lottery.fetcher.lotterydraw.LotteryDrawPrizeItem;
import com.lehecai.core.util.CoreDateUtils;
import com.lehecai.core.util.CoreFetcherUtils;

/**
 * 山东彩票网 开奖结果抓取
 * 主要抓取齐鲁风采23选5  <br/>
 * 历史地址:http://app.sdcp.cn/fccms/site/num/235kjgg.jsp<br/>
 * @author 
 *
 */
public class LotteryDrawFetch518WorkerOfficial extends AbstractLotteryDrawFetchWorker{

	protected final Logger logger = LoggerFactory.getLogger(this.getClass().getName());
	protected static final String RESULT_LOCALITY_URL = "http://stat.sdcp.cn/kjgg235.htm?";
	protected static final String RESULT_HISTORY_LOCALITY_URL = "http://app.sdcp.cn/fccms/site/num/235kjgg.jsp";
    protected static final String RESULT_LOCALITY_CACHE_URL = "http://stat.sdcp.cn/235kjgg.htm";//官网缓存最新开奖结果的页面数据

	protected String siteName = "山东彩票网";
	protected String lotteryScope = "齐鲁风采23选5";
	
	public LotteryDrawFetch518WorkerOfficial(){
		super(LotteryType.A_QLFC23);
	}
	@Override
	public LotteryDraw fetchResult(String phase) {
		return null;
	}
	
	private String fetchLatestLotteryPhase() {
		long random = (new Date()).getTime();
		String url = RESULT_LOCALITY_URL + random;
		String data = null;
		String pageInfo = "彩期为null时获取结果页面" + url;
		String encoding = "GBK";
		String logHeader = "==" + lotteryScope + "==" + siteName + "==" + pageInfo + "==抓取==" + getLotteryType().getName() + "==";
		
		String phase = "";		
		try {
			data = CoreFetcherUtils.URLGet(url, null, encoding);
		} catch (Exception e) {
			logger.error("获取html数据失败" + e.getMessage());
			return null;
		}
		
		if (data == null || data.indexOf("404 Not Found") > 0 || data.isEmpty()) {
			logger.error(logHeader + "data is null or 404 Not Found");
			return null;
		}
		
		Parser parser = null;
		try {
			parser = Parser.createParser(data,  encoding);
		} catch (Exception e) {
			logger.error("解析html页面失败" + e.getMessage());
			return null;
		}
		
		NodeFilter filter = new HasAttributeFilter("class", "grey666");
		NodeList nodeList = null;
		try {
			nodeList = parser.extractAllNodesThatMatch(filter);
			ParagraphTag paragraphTag = (ParagraphTag) nodeList.elementAt(0);
			String[] tempArray = StringUtils.split(paragraphTag.toPlainTextString(), "  ");
			String tempPhase = tempArray[1].trim().split("第")[1];
			phase = StringUtils.replace(tempPhase, "期", "");
		} catch (ParserException e) {
			logger.error("数据解析错误==" + e.getMessage(), e);
			return null;
		}
		return phase;
	}

	@Override
	public LotteryDraw fetchResultDetail(String phase) {
        String latesPhase = fetchLatestLotteryPhase();//得到最新彩期
        String url = "";
        String data = null;
        String encoding = "GBK";
        LotteryDraw lotteryDraw = new LotteryDraw();

        if (latesPhase != null && (phase == null || "".equals(phase) || latesPhase.equals(phase))) { //如果传入的彩期为null值 或者是最新彩期，此时通过抓取官网的缓存页面获取即可
            phase = latesPhase;
            url = String.format(RESULT_LOCALITY_CACHE_URL, phase);
            try {
                data = CoreFetcherUtils.URLGet(url, null, encoding);
            } catch (Exception e) {
                logger.error("获取html数据失败" + e.getMessage());
                return null;
            }
        } else {
            if (phase == null || "".equals(phase)) {
                phase = latesPhase;
                if (StringUtils.isEmpty(phase)) {
                    return null;
                }
            }
            url = String.format(RESULT_HISTORY_LOCALITY_URL, phase);
            try {
                Map<String, String> params = new HashMap<String, String>();
                params.put("sqi", phase);
                data = CoreFetcherUtils.URLPost(url, params, encoding);
            } catch (Exception e) {
                logger.error("获取html数据失败" + e.getMessage());
                return null;
            }
        }
		String pageInfo = "结果页面" + url;
		String logHeader = "==" + lotteryScope + "==" + siteName + "==" + pageInfo + "==抓取==" + getLotteryType().getName() + "==";

		if (data == null || data.indexOf("404 Not Found") > 0 || data.isEmpty()) {
			logger.error(logHeader + "data is null or 404 Not Found");
			return null;
		}	
		Parser parser = null;
		try {
			parser = Parser.createParser(data,  encoding);
		} catch (Exception e) {
			logger.error("解析html页面失败" + e.getMessage());
			return null;
		}
		
		String strResult = "";
		NodeFilter phaseFilter = new TagNameFilter("option");
		NodeFilter numberFilter = new HasAttributeFilter("class", "sum clearfix");
		NodeFilter detailFilter = new TagNameFilter("table");
		NodeFilter timeFilter = new HasAttributeFilter("class", "grey333");
		NodeFilter saleFilter = new HasAttributeFilter("class", "ukjgg");
		try {
			NodeList optionNodeList = parser.extractAllNodesThatMatch(phaseFilter);
			
			//彩期验证
			OptionTag optionTag = (OptionTag) optionNodeList.elementAt(0);
			String tempPhase = optionTag.toPlainTextString().trim();
			if (!phase.equals(tempPhase)) {
				logger.error("详细页面option中第一个彩期与传入彩期不一致");
				return null;
			}
			lotteryDraw.setPhase(tempPhase);
			lotteryDraw.setLotteryType(this.getLotteryType());
			lotteryDraw.setJackpot(null);
			
			//中奖号码
			parser.setInputHTML(data);
			NodeList paragraphNodeList = parser.extractAllNodesThatMatch(numberFilter);
			ParagraphTag paragraphTag =(ParagraphTag)paragraphNodeList.elementAt(0);
			NodeList numberNodeList = paragraphTag.getChildren();
			int num = 0;
			for (int i=0; i<numberNodeList.size(); i++) {
				Node tempNode = (Node)numberNodeList.elementAt(i);
				if (tempNode instanceof LinkTag) {
					if (num > 0) {
						strResult += ",";
					}
					strResult += tempNode.toPlainTextString().trim();
					num++;
				}
			}
			lotteryDraw.setResult(strResult);
			
			//中奖明细
			List<LotteryDrawPrizeItem> drawItemList = new ArrayList<LotteryDrawPrizeItem>();
			parser.setInputHTML(data);
			NodeList tableNodeList = parser.extractAllNodesThatMatch(detailFilter);
			TableTag tableTag = (TableTag)tableNodeList.elementAt(0);
			TableRow[] tableRowArray = tableTag.getRows();
			for (int i=0; i<tableRowArray.length; i++) {
				if (i > 0 && i<=3) {
					TableRow tableRow = tableRowArray[i];
					TableColumn[] columnArray = tableRow.getColumns();
					LotteryDrawPrizeItem item = new LotteryDrawPrizeItem();
					item.setName(columnArray[0].toPlainTextString().trim());
					item.setWinningCount(columnArray[1].toPlainTextString().trim());
					item.setPrizeAmount(columnArray[2].toPlainTextString().trim());
					drawItemList.add(item);
				}
			}
			lotteryDraw.setResultDetail(drawItemList);
			
			//开奖时间
			parser.setInputHTML(data);
			NodeList timeNodeList = parser.extractAllNodesThatMatch(timeFilter);
			String timeStr = timeNodeList.elementAt(0).toPlainTextString().trim();
			timeStr = StringUtils.split(timeStr, "  ")[0];
			lotteryDraw.setTimeDraw(CoreDateUtils.formatDate(CoreDateUtils.parseDate(timeStr, "yyyy年MM月dd日"), CoreDateUtils.DATE));
			
			//销售总额
			parser.setInputHTML(data);
			NodeList saleNodeList = parser.extractAllNodesThatMatch(saleFilter);
			logger.info(saleNodeList.elementAt(0).toHtml());
			String saleStr = saleNodeList.elementAt(0).toPlainTextString().trim();
			String[] salsArray = StringUtils.split(saleStr, "&nbsp;");
			
			if (salsArray.length == 3 && !StringUtils.isEmpty(salsArray[1]) && Integer.valueOf(salsArray[1]) > 0) {
				lotteryDraw.setVolumeOfSales(salsArray[1]);
			}
		} catch (ParserException e) {
			logger.error("数据解析错误==" + e.getMessage(), e);
			return null;
		}
		return lotteryDraw;
	}

	@Override
	protected String getResultDetailUrl(String phase) {
		return null;
	}

	@Override
	protected String getResultUrl(String phase) {
		return null;
	}

}
